import { app, BrowserWindow, Menu, ipcMain } from 'electron';
import * as path from 'path';
import { WindowManager } from './window';
import { MenuManager } from './menu';
import { IPCManager } from './ipc';

class Application {
  private windowManager: WindowManager;
  private menuManager: MenuManager;
  private ipcManager: IPCManager;

  constructor() {
    this.windowManager = new WindowManager();
    this.menuManager = new MenuManager();
    this.ipcManager = new IPCManager(this.windowManager);
  }

  public async initialize(): Promise<void> {
    try {
      // 设置应用程序用户模型ID (Windows)
      if (process.platform === 'win32' && app) {
        app.setAppUserModelId('com.example.ssh-client');
      }

      // 应用程序事件监听
      if (app) {
        app.whenReady().then(() => {
          this.onReady();
        });

        app.on('window-all-closed', () => {
          if (process.platform !== 'darwin') {
            app.quit();
          }
        });

        app.on('activate', () => {
          if (BrowserWindow.getAllWindows().length === 0) {
            this.windowManager.createMainWindow();
          }
        });

        // 安全设置
        app.on('web-contents-created', (_, contents) => {
          contents.setWindowOpenHandler(() => {
            return { action: 'deny' };
          });
        });
      }
    } catch (error) {
      console.error('Error in application initialization:', error);
      if (app) {
        app.quit();
      }
    }
  }

  private onReady(): void {
    // 创建主窗口
    this.windowManager.createMainWindow();

    // 设置菜单
    this.menuManager.setupMenu();

    // 初始化IPC通信
    this.ipcManager.initialize();

    // 开发环境下打开开发者工具
    if (process.env.NODE_ENV === 'development') {
      const mainWindow = this.windowManager.getMainWindow();
      if (mainWindow) {
        mainWindow.webContents.openDevTools();
      }
    }
  }
}

// 创建应用程序实例并初始化
const application = new Application();
application.initialize().catch((error) => {
  console.error('Failed to initialize application:', error);
  app.quit();
});